import axios from 'axios';
import configs from '../config';

const instance = axios.create();
instance.defaults.withCredentials = true;
instance.defaults.baseURL = configs.apiHost;
instance.interceptors.request.use(function(config) {
    // Do something before request is sent
    // TODO lowcase
    if (config.method === 'post') {
        config.data = config.data || {};
        config.data.token = configs.token;
        config.data.productType = configs.productType;
        // let data = {};
        // data = {
        //     ...config.data,
        //     token: configs.token,
        //     productType: configs.productType
        // };
        // config.data = qs.stringify(data);
    }
    if (config.method === 'get') {
        config.params = config.params || {};
        config.params.token = configs.token;
        config.params.productType = configs.productType;
    }
    return config;
}, function(error) {
    // Do something with request error
    return Promise.reject(error);
});
instance.interceptors.response.use(function(response) {
    // Do something with response data
    if (response.status === 200) {
        if (response.data && response.data.code === 1) return response.data && response.data.data;
        return Promise.reject(response.data);
    }
}, function(error) {
    // Do something with response error
    return Promise.reject(error);
});

export default instance;
